package com.cnsugar.common.jdbc.dialect;

import com.cnsugar.common.jdbc.dialect.db.MySQLDialect;
import com.cnsugar.common.jdbc.dialect.db.OracleDialect;
import com.cnsugar.common.jdbc.dialect.db.PhoenixDialect;
import com.cnsugar.common.jdbc.dialect.db.SQLiteDialect;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by sugar on 17/10/14.
 */
public class DialectUtils {
    private final static Map<Object, Dialect> map = new HashMap<>();

    public final static Dialect getDialect(JdbcTemplate jt) {
        Dialect dialect = map.get(jt);
        if (dialect != null) {
            return dialect;
        }
        try {
            dialect = getDialect(jt.getDataSource().getConnection());
            map.put(jt, dialect);
            return dialect;
        } catch (SQLException e) {
            throw new RuntimeException("Can't get the database product name .");
        }
    }

    public final static Dialect getDialect(DataSource dataSource) {
        Dialect dialect = map.get(dataSource);
        if (dialect != null) {
            return dialect;
        }
        try {
            dialect = getDialect(dataSource.getConnection());
            map.put(dataSource, dialect);
            return dialect;
        } catch (SQLException e) {
            throw new RuntimeException("Can't get the database product name .");
        }
    }

    public final static Dialect getDialect(Connection conn) {
        String name = null;
        try {
            name = conn.getMetaData().getDatabaseProductName();
        } catch (SQLException e) {
            throw new RuntimeException("Can't get the database product name .");
        }
        if (MySQLDialect.NAME.equalsIgnoreCase(name)) {
            return MySQLDialect.getInstance();
        } else if (OracleDialect.NAME.equalsIgnoreCase(name)) {
            return OracleDialect.getInstance();
        } else if (SQLiteDialect.NAME.equalsIgnoreCase(name)) {
            return SQLiteDialect.getInstance();
        } else if (PhoenixDialect.NAME.equalsIgnoreCase(name)) {
            return PhoenixDialect.getInstance();
        } else {
            throw new RuntimeException("Get dialect error.");
        }
    }
}
